#include "sg_interface.h"

using namespace std;
using namespace suggestion;

sgI::sgI(Ice::PropertiesPtr props, CACHE_MAP *cacheMap) : __cache(cacheMap) {
    __isCache = props->getPropertyAsIntWithDefault("server.Cache", 1);
    string commPath = props->getPropertyWithDefault("server.Dict.File", "");
    __indexer = new sgIndexer((char *)commPath.c_str());
}

sgI::~sgI() {
    delete __indexer;
}

VectorUid
sgI::doSearch(const string &query, const VectorSg &sgData, Ice::Long sessionId, const Ice::Current&) {
    // 初始化变量
    VectorUid reData;
    MYLOG_INFO << "start doSearch" ;
    MAP_VEC __mapIndex; // 索引集和
    const char *query_char = query.c_str();
    int query_char_len = query.length();

    // cache index
    if(1 == __isCache)
        __mapIndex = __cache->fetch(sessionId);

    if(__mapIndex.size() < 1) {
        int count = sgData.size();
        int i;
        for(i = 0; i < count; i++) {
            // 生成索引集合
            __indexer->indexer((uint8_t *)(sgData[i].text.c_str()), sgData[i].text.length(), sgData[i].index, __mapIndex);
        }

        // add into cache
        __cache->insert(sessionId, __mapIndex);
    }

    int indexNum = 0;
    MAP_VEC::iterator map_it = __mapIndex.begin();
    VectorUid::iterator list_row;
    while(map_it != __mapIndex.end()) {
        if(0 == strncmp((map_it->first).c_str(), query_char, query_char_len)) {
            for(list_row = (map_it->second).begin(); list_row != (map_it->second).end();) {
                reData.push_back(*list_row);
                list_row++;
            }
        }
        map_it++;
        indexNum++;
    }

    // log
    MYLOG_INFO << "Indexed number: " << indexNum << "\t- Searched number: " << reData.size();

    return reData;
}
